package com.siki.utils;

import com.github.pagehelper.Page;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

/**
 * @Author Siki
 * @Date 2020/4/24
 * @Description Mybatis pagehelp封装
 */

@NoArgsConstructor
@Setter
@Getter
@SuppressWarnings({"rawtypes", "unchecked"})
public class PageableBuilder<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    //当前页
    private int pageNum;
    //每页的数量
    private int pageSize;
    //总记录数
    private long total;
    //总页数
    private int pages;
    //结果集
    private List<T> list;
    //是否为第一页
    private boolean isFirstPage = false;
    //是否为最后一页
    private boolean isLastPage = false;

    /**
     * 根据传入对象进行包装
     *
     * @param list
     */
    public PageableBuilder(T list) {
        if (list instanceof Page) {
            Page page = (Page) list;
            this.pageNum = page.getPageNum();
            this.pageSize = page.getPageSize();
            this.pages = page.getPages();
            this.list = page;
            this.total = page.getTotal();
        } else if (list instanceof Collection) {
            List<T> thisList = (List<T>) list;
            this.pageNum = 1;
            this.pageSize = thisList.size();
            this.pages = 1;
            this.list = thisList;
            this.total = thisList.size();
        }
        if (list instanceof Collection) {
            //确定分页边界
            judgePageBoudary();
        }
    }
    public PageableBuilder(List<T> list,Integer pageNum,Integer count){
        this.pageNum = null==pageNum? 1:pageNum;
        this.pageSize = list.size();
        this.pages = count/this.pageSize +1 ;
        this.list = list;
        this.total = list.size();
    }

    /**
     * 确定传进来的集合边界，以免越界
     */
    private void judgePageBoudary(){
        isFirstPage = pageNum ==1;
        isLastPage = pageNum ==pages;
    }


    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("PageInfo{");
        sb.append("pageNum=").append(pageNum);
        sb.append(", pageSize=").append(pageSize);
        sb.append(", total=").append(total);
        sb.append(", pages=").append(pages);
        sb.append(", list=").append(list);
        sb.append(", isFirstPage=").append(isFirstPage);
        sb.append(", isLastPage=").append(isLastPage);
        sb.append(", navigatepageNums=");
        sb.append('}');
        return sb.toString();
    }
}















